package com.movie.utils;

import com.movie.beans.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

import static org.apache.commons.beanutils.PropertyUtils.copyProperties;

public class ShiroUtil {
    public static String randomSalt()
    {
        // 一个Byte占两个字节，此处生成的3字节，字符串长度为6
        SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
        String hex = secureRandom.nextBytes(3).toHex();
        return hex;
    }

    public static Subject getSubject()
    {
        return SecurityUtils.getSubject();
    }

    public static SysUser getSysUser(){
        SysUser user = null;
        Object obj = getSubject().getPrincipal();
        if (obj!=null)
        {
            user = new SysUser();
            try {
                copyProperties(user, obj);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        return user;
    }

    public static void setSysUser(SysUser user)
    {
        Subject subject = getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }
    public static String getIp()
    {
        return getSubject().getSession().getHost();
    }
}
